package com.lsh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lsh.dao.CommentDao;
import com.lsh.dao.UserDao;
import com.lsh.dao.UserDatumDao;
import com.lsh.dao.UserTokenDao;
import com.lsh.dao.advices.AdviceCommentDao;
import com.lsh.domain.AdviceComment;
import com.lsh.domain.UserComment;
import com.lsh.domain.UserReply;
import com.lsh.service.CommentService;
import com.lsh.service.advices.AdviceCommentService;
import com.lsh.util.PageUtil;
import com.lsh.util.PraiseRedisUtil;
import jdk.nashorn.internal.parser.Token;
import net.sf.json.JSONObject;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.jms.Destination;
import java.util.*;

@Service
public class CommentServiceImpl implements CommentService {

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @Resource
    JmsTemplate jmsTemplate;

    private static Destination destination = new ActiveMQQueue("queue.comment");

    @Autowired
    UserTokenDao userTokenDao;
    @Autowired
    UserDao userDao;
    @Autowired
    CommentDao commentDao;
    @Autowired
    AdviceCommentDao adviceCommentDao;


    /**
     * 评价列表
     * @param artId
     * @return
     */
    @Override
    public List<HashMap<String, Object>> getCommentList(String artId, String token) {
        String userId = userTokenDao.getByToken(token);
        List<HashMap<String, Object>> commentList = commentDao.findCommentList(artId, userId);
        for(HashMap map: commentList){
            String isPraise = (String) redisTemplate.opsForHash().get(PraiseRedisUtil.PRAISE_COMMENT_USER_LIKE_MAP, map.get("id") + "::" + userId);
            if(isPraise != null){
                map.put("isPraise", isPraise);
            }
            String redisCount = (String)redisTemplate.opsForHash().get(PraiseRedisUtil.PRAISE_COMMENT_USER_LIKE_COUNT, map.get("id") + "");
            if(redisCount != null){
                int count = (int) map.get("praise_num");
                map.put("praise_num", count + Integer.parseInt(redisCount));
            }
        }
        return commentList;
    }

    /**
     * 发表评价
     * @param token
     * @param userComment
     * @return
     */
    @Override
    public String publishComment(String token, UserComment userComment) {
        int userId = Integer.parseInt(userTokenDao.getByToken(token));
        String username = userDao.getUsername(userId);
        userComment.setCommentUid(userId);
        userComment.setCommentUserName(username);
        int result = commentDao.saveComment(userComment);
        if(result > 0){ //评价成功后，向指定消息队列发送消息
            AdviceComment ac = adviceCommentDao.findAdviceCommentBycommentId(userComment.getId());
            ac.setFromUserName(userComment.getCommentUserName());
            ac.setIsRead(0);
            ac.setType(0);
            redisTemplate.opsForList().leftPush("comment_" + ac.getToUid(), ac);
            int toUid = commentDao.findUserIdByCommentId(userComment.getId());
            jmsTemplate.convertAndSend(destination, toUid);
        }
        return (result > 0) ? "200" : "0";
    }

    /**
     * 回复列表
     * @param commentId
     * @return
     */
    @Override
    public List<HashMap<String, Object>> getReplyList(String commentId, String token) {
        String userId = userTokenDao.getByToken(token);
        List<HashMap<String, Object>> replyList = commentDao.findReplyList(commentId, userId);
        return replyList;
    }

    /**
     * 用户回复
     * @param token
     * @param userReply
     * @return
     */
    @Override
    public String publishReply(String token, UserReply userReply) {
        int fromUserId = Integer.parseInt(userTokenDao.getByToken(token));
        String username = userDao.getUsername(fromUserId);
        int toUserId = userDao.getUserId(userReply.getToUsername());
        userReply.setFromUid(fromUserId);
        userReply.setFromUsername(username);
        userReply.setToUid(toUserId);
        int result = commentDao.saveReply(userReply);
        if(result > 0) { //回复成功后，向指定消息队列发送消息
            AdviceComment ac = adviceCommentDao.findAdviceReplyByreplyId(userReply.getId());
            ac.setFromUserName(userReply.getToUsername());
            ac.setToUid(String.valueOf(userReply.getToUid()));
            ac.setToUserName(userReply.getToUsername());
            ac.setContent(userReply.getReplyComment());
            ac.setIsRead(0);
            ac.setType(1);
            redisTemplate.opsForList().leftPush("comment_" + toUserId, ac);
            jmsTemplate.convertAndSend(destination, userReply.getToUid());
        }
        return (result == 1) ? "200" : "0";
    }

    /**
     * 删除评价
     * @param token
     * @param commentId
     * @return
     */
    @Override
    public String deleteComment(String token, String commentId) {
        String userId = userTokenDao.getByToken(token);
        int result = commentDao.deleteComment(userId, commentId);
        return (result == 1) ? "200" : "0";
    }


    /**
     * 删除回复
     * @param token
     * @param ReplyId
     * @return
     */
    @Override
    public String deleteReply(String token, String ReplyId) {
        String userId = userTokenDao.getByToken(token);
        int result = commentDao.deleteReply(userId, ReplyId);
        return (result == 1) ? "200" : "0";
    }


    /**
     * 点赞评价
     * @param token
     * @return
     */
    @Override
    public String praiseComment(String token, String commentId) {
        String code = null;
        int message = 0;
        String userId = userTokenDao.getByToken(token);
        int result = commentDao.findPraise(userId, commentId);
        if(result == 0) {
            boolean bool = commentDao.savePraise(userId, commentId);
            if(bool == true){
                commentDao.updateCommentPraiseNum(commentId, "add");
                code = "200";
                message = 1;
            }else{
                code = "0";
            }
        }else{
            boolean bool = commentDao.deletePraise(userId, commentId);
            if(bool == true){
                commentDao.updateCommentPraiseNum(commentId, "sub");
                code = "200";
                message = -1;
            }else{
                code = "0";
            }
        }
        JSONObject jo = new JSONObject();
        jo.put("code", code);
        jo.put("message", message);
        return jo.toString();
    }

    /**
     * 点赞回复
     * @param token
     * @param replyId
     * @return
     */
    @Override
    public String praiseReply(String token, String replyId) {
        String code = null;
        int message = 0;
        String userId = userTokenDao.getByToken(token);
        int result = commentDao.findReplyPraise(userId, replyId);
        if(result == 0) {
            boolean bool = commentDao.saveReplyPraise(userId, replyId);
            if(bool == true){
                commentDao.updateReplyPraiseNum(replyId, "add");
                code = "200";
                message = 1;
            }else{
                code = "0";
            }
        }else{
            boolean bool = commentDao.deleteReplyPraise(userId, replyId);
            if(bool == true){
                commentDao.updateReplyPraiseNum(replyId, "sub");
                code = "200";
                message = -1;
            }else{
                code = "0";
            }
        }
        JSONObject jo = new JSONObject();
        jo.put("code", code);
        jo.put("message", message);
        return jo.toString();
    }

    /**
     * 根据id和页码查询评价数据
     * @param pageNum
     * @param userId
     * @return
     */
    @Override
    public PageInfo findCommentPage(Integer pageNum, String userId) {
        PageHelper.startPage(pageNum, PageUtil.MANAGE_COMMENT.getPageSize());
        List userCommentList = commentDao.findCommentAllByUid(userId);
        PageInfo pageInfo = new PageInfo<>(userCommentList);
        return pageInfo;
    }

    /**
     * 根据用户id和评价id删除对应评价
     * 包括该评价下的回复（这里使用数据库的级联即可，无需额外代码操作）
     * @param commentId
     * @param userId
     */
    @Override
    public int deleteCommentById(String commentId, String userId) {
        int result = commentDao.deleteCommentById(commentId, userId);
        return result;
    }

    /**
     * 根据id和页码查询回复数据
     * @param pageNum
     * @param userId
     * @return
     */
    @Override
    public PageInfo<UserReply> findReplyPage(Integer pageNum, String userId) {
        PageHelper.startPage(pageNum, PageUtil.MANAGE_COMMENT.getPageSize());
        List<LinkedHashMap<String, Object>> userReplyList = commentDao.findReplyAllByUid(userId);
        PageInfo pageInfo = new PageInfo(userReplyList);
        return pageInfo;
    }

    /**
     * 根据用户id和回复id删除对应回复
     * @param replyId
     * @param userId
     */
    @Override
    public int deleteReplyById(String replyId, String userId) {
        int result = commentDao.deleteReplyById(replyId, userId);
        return result;
    }

}
